<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016 杭州博也网络科技, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Shop\Controller;
use Admin\Api\ConfigApi;
use Common\Api\BoyeServiceApi;
use Common\ConstVar\BoyeActionConstModel;
use Common\Model\SessionModel;
use Shop\Api\ShoppingCartApi;
use Shop\Api\WalletApi;
use Shop\Api\ZjportOrderStatusApi;
use Think\Controller;

class ShopController extends  Controller {
	
	protected $userinfo;
	protected $wxaccount;
	protected $wxapi;
	protected $openid;
    protected $themeType;
    protected $remoteApi;
	
	protected function _initialize() {
        header("X-Copyright:http://www.itboye.com");
        header("X-Request-Time:".date('Y-m-d H:i:s',time()));
		// 获取配置
		$this -> getConfig();

		if (!defined('APP_VERSION')) {
			//定义版本
			if (defined("APP_DEBUG") && APP_DEBUG) {
				define("APP_VERSION", time());
			} else {
				define("APP_VERSION", C('APP_VERSION'));
			}
		}

		C('SHOW_PAGE_TRACE', false);//设置不显示trace

        $this->remoteApi = new BoyeServiceApi();
        $this->themeType = "desktop_default";


        $this->userinfo=session('user');
        $cart_item_count = $this->countShoppingCart();
        //当前 在线session数目
        $online_session = $this->countSession();
        $this->assign('online_session',$online_session);
        $this->assign('user',$this->userinfo);
        $this->assign("cart_item_count",$cart_item_count);
	}

    protected function countSession(){
        S('global_online_session',null);
        $cnt = S('global_online_session');
        if(empty($cnt)){
            $model = new SessionModel();
            $cnt = $model->count();
            S('global_online_session',$cnt,600);
        }

        return $cnt;
    }

    protected function checkLogin(){

        if(empty($this->userinfo)){
            $this->error("请登录后操作!",U('Shop/Index/login'));
        }
    }

    protected function updateUserinfo($userinfo){
        session("user",$userinfo);
        $this->assign('user',$userinfo);
    }

    /**
     * 更新头像
     * @param $id
     */
    protected function updateAvatar($id){
        $this->userinfo['head'] = getImageUrl($id);
        session("user",$this->userinfo);
    }

    protected function updateDefaultAddress($id){
        $this->userinfo['default_address'] = $id;
        session("user",$this->userinfo);
    }

    /**
     * 清除购物车商品数的缓存
     */
    protected function  clearCartItemCache(){
        S('cart_item_count_'.$this->userinfo['uid'],null);
    }

    /**
     * 计算购物车数目
     * @return mixed
     */
    protected function countShoppingCart(){

        $cart_item_count = S('cart_item_count_'.$this->userinfo['uid']);

        if(!empty($cart_item_count)){
            return $cart_item_count;
        }

        $uid = $this->userinfo['id'];

        $map = array(
            'uid'=>$uid,
        );

        $result = apiCall(ShoppingCartApi::COUNT,array($map));

        if($result['status']){
            $cart_item_count = $result['info'];
            //缓存1200秒
            S('cart_item_count_'.$this->userinfo['uid'],$cart_item_count,1200);
            return $cart_item_count;
        }else{
            LogRecord($result['info'],"计算购物车数目!");
        }
    }

	/**
	 * 从数据库中取得配置信息
	 */
	protected function getConfig() {
		$config = S('config_' . session_id() . '_' . session("uid"));

		if ($config === false) {
			$map = array();
			$fields = 'type,name,value';
			$result = apiCall(ConfigApi::QUERY_NO_PAGING, array($map, false, $fields));
			if ($result['status']) {
				$config = array();
				if (is_array($result['info'])) {
					foreach ($result['info'] as $value) {
						$config[$value['name']] = $this -> parse($value['type'], $value['value']);
					}
				}
				//缓存配置300秒
				S("config_" . session_id() . '_' . session("uid"), $config, 300);
			} else {
				LogRecord('INFO:' . $result['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
				$this -> error($result['info']);
			}
		}
		C($config);
	}

    /**
     * 根据配置类型解析配置
     * @param  integer $type 配置类型
     * @param  string $value 配置值
     * @return array|string
     */
	private static function parse($type, $value) {
		switch ($type) {
			case 3 :
				//解析数组
				$array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
				if (strpos($value, ':')) {
					$value = array();
					foreach ($array as $val) {
						list($k, $v) = explode(':', $val,2);
						$value[$k] = $v;
					}
				} else {
					$value = $array;
				}
				break;
		}
		return $value;
	}

    protected function checkApiCallResult($result,$cantBeNull=true){

        if(!$result['status']){
            $this->error($result['info']);
        }

        if($cantBeNull && is_null($result['info'])){
            $this->error("获取信息为空!");
        }

    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _post($key,$default='',$emptyErrMsg=''){
        $value = I("post.".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->error($emptyErrMsg);
        }
        return $value;
    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _get($key,$default='',$emptyErrMsg=''){
        $value = I("get.".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->error($emptyErrMsg);
        }
        return $value;
    }

}
